# -*- coding: utf-8 -*-
'''
Created on Apr 26, 2011

@author: Yang Sun
'''

import sys
import os
import xbmc
import xbmcgui
import xbmcplugin
import urllib
import video.pptv
import log
pptv = video.pptv

class PPTVUI:
    def __init__(self):
        pass
    
    def getParams(self, paramString):
        commands = {}
        splitCommands = paramString[paramString.find('?')+1:].split('&')
        
        for command in splitCommands: 
            if (len(command) > 0):
                splitCommand = command.split('=')
                name = splitCommand[0]
                value = splitCommand[1]
                commands[name] = value
        
        return commands
    
    '''
    type
    filter
    '''
    def listMenu(self, params = {}):
        get = params.get
        cache = True
        
        totalItemSize = len(pptv.type) + 1
        
        if(get('action') is None):     
            log.info('Process Root List Action')   
            for type in pptv.type:
                self.addFolderListItem({'action' : 'get_program',                                     
                                        'type' : '1',
                                        'tag' : '|||||'
                                        }, 
                                       type, totalItemSize)
            
            #self.addFolderListItem(params, {'Title' : '搜索'})
            
            xbmcplugin.setContent(int(sys.argv[1]), 'type')   
            xbmcplugin.endOfDirectory( handle=int(sys.argv[1]))       
             
        if(get('action') == 'get_program'):
            log.info('Process Get Program Action')
            type = get('type')
            tags = get('tag')
            programs = pptv.getProgram(type, tags)
            for prog in programs:
                print prog            
            
        
    #================================== List Item manipulation =========================================    
    # is only used by List Menu
    def addListItem(self, params = {}, item_params = {}):
        get = params.get
        item = item_params.get
        
        if (not item("action")):             
            self.addFolderListItem(params, item_params)                            
        else :
            self.addActionListItem(params, item_params)
    
    # common function for adding folder items
    def addFolderListItem(self, params = {}, item_params = {}, size = 0):
        get = params.get
        item = item_params.get
        
        icon = "DefaultFolder.png"        
        
        thumbnail = item('thumbnail', 'DefaultFolder.png')
                
        cm = self.addContextMenuItems(params, item_params)
        
        if (thumbnail.find('http://') == -1):            
            thumbnail = self.getThumbnail(thumbnail)
        
        print 'thumbnail is %s' % thumbnail
        listitem=xbmcgui.ListItem( label=item('Title'), iconImage = icon, thumbnailImage=thumbnail)
        url = '%s?%s' % ( sys.argv[0], item("path") )
        url = self.buildItemUrl(params, url)
        if len(cm) > 0:
            listitem.addContextMenuItems( cm, replaceItems=False )
        
        listitem.setProperty( "Folder", "true" ) 
        log.info('url = %s' % url)       
        xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=True, totalItems=size)
        
    # common function for adding action items
    def addActionListItem(self, params = {}, item_params = {}, size = 0):
        pass
    
    # common function for adding video items
    def addVideoListItem(self, params = {}, item_params = {}, listSize = 0): 
        pass
    
    def addContextMenuItems(self, params = {}, item_params = {}):
        cm = []
        return cm
    
    def getThumbnail( self, title ):
        if (not title):
            title = "DefaultFolder.png"
        else:
            title = "DefaultFolder.png"
        '''
        thumbnail = os.path.join( sys.modules[ "__main__" ].__plugin__, title + ".png" )
        
        if ( not xbmc.skinHasImage( thumbnail ) ):
            thumbnail = os.path.join( self.plugin_thumbnail_path, title + ".png" )
            if ( not os.path.isfile( thumbnail ) ):
                thumbnail = "DefaultFolder.png"    
        
        return thumbnail
        '''
        thumbnail = 'DefaultFolder.png'
        return thumbnail 
    
    def buildItemUrl(self, item_params = {}, url = ''):   
        index = 1     
        for k, v in item_params.items():
            #if (k != "path" and k != "thumbnail" and k!= "playlistId" and k!= "next" and k != "content" and k!= "editid"
            #    and k!= "summary" and k!= "published" and k!="Title" and k!= "Title" ):
            if(index < len(item_params)):
                url += k + "=" + urllib.quote(v) + "&"
            else:
                url += k + "=" + urllib.quote(v)
            index += 1
        return url
        